<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="作物生长记录"></page-header>

        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的作物内容"
                v-model="searchKeyword"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>

        <view class="list-filter-container">
            <view class="filter-picker" @click="openDatePopup">
                <text class="picker-label">{{ selectedTime || '时间' }}</text>
                <text class="picker-arrow">
                    <roc-icon-plus
                        type="fas"
                        name="angle-down"
                        :size="16"
                        color="#2E6140"></roc-icon-plus>
                </text>
            </view>
            <picker
                mode="selector"
                :range="growthStageOptions"
                range-key="name"
                @change="onGrowthStageChange">
                <view class="filter-picker">
                    <text class="picker-label">{{ selectedGrowthStage?.name || '生长阶段' }}</text>
                    <text class="picker-arrow">
                        <roc-icon-plus
                            type="fas"
                            name="angle-down"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </text>
                </view>
            </picker>
            <picker
                mode="selector"
                :range="areaOptions"
                range-key="name"
                :value="selectedAreaIndex"
                @change="onAreaChange">
                <view class="filter-picker">
                    <text class="picker-label">
                        {{ areaOptions[selectedAreaIndex]?.name || '地块' }}
                    </text>
                    <text class="picker-arrow">
                        <roc-icon-plus
                            type="fas"
                            name="angle-down"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </text>
                </view>
            </picker>
        </view>

        <!-- 日期选择弹出层 -->
        <uni-popup ref="datePopup" type="center">
            <view class="popup-content">
                <view class="popup-title">选择日期范围</view>
                <view class="date-picker-container">
                    <view class="date-item">
                        <text>开始日期：</text>
                        <picker
                            mode="date"
                            :value="tempStartDate || startDate"
                            @change="onStartDateChange">
                            <view class="picker-value">
                                {{ tempStartDate || startDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                    <view class="date-item">
                        <text>结束日期：</text>
                        <picker
                            mode="date"
                            :value="tempEndDate || endDate"
                            :start="tempStartDate || startDate"
                            @change="onEndDateChange">
                            <view class="picker-value">
                                {{ tempEndDate || endDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="popup-buttons">
                    <button class="btn cancel" @click="cancelDatePicker">取消</button>
                    <button class="btn confirm" @click="confirmDatePicker">确定</button>
                </view>
            </view>
        </uni-popup>

        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredGrowthRecords"
                :key="index"
                :item="item"
                @clickItem="viewDetail(item)"
                @edit="editRecord(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <text class="date-text">
                            {{ formatDate(item.startDate || item.createTime) }}
                        </text>
                        <roc-icon-plus
                            type="fas"
                            name="angle-right"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <div style="display: flex; justify-content: space-between">
                            <view class="info-row">
                                <text class="info-label">地块/条田</text>
                                <text class="info-value">
                                    {{ item.plotName }}-{{ item.fieldName }}
                                </text>
                            </view>

                            <view class="info-row">
                                <text class="info-label">作物名称</text>
                                <text class="info-value">{{ item.cropName }}</text>
                            </view>
                        </div>

                        <view class="info-row">
                            <text class="info-label">生长阶段</text>
                            <text class="info-value">
                                {{ item.growthStage }} {{ item.growthStageSubclass }}
                            </text>
                        </view>

                        <view class="info-row">
                            <text class="info-label">面积</text>
                            <text class="info-value">{{ item.area || 0 }} 亩</text>
                        </view>

                        <view class="info-row">
                            <text class="info-label">负责人</text>
                            <text class="info-value">{{ item.personInCharge || '未设置' }}</text>
                        </view>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>
                        <view class="info-columns">
                            <view class="info-column">
                                <text class="column-label">叶面积</text>
                                <text class="column-value">{{ item.leafArea }} cm²</text>
                            </view>

                            <view class="info-column">
                                <text class="column-label">株高</text>
                                <text class="column-value">{{ item.plantHeight }} cm</text>
                            </view>

                            <view class="info-column">
                                <text class="column-label">叶龄</text>
                                <text class="column-value">{{ item.leafAge }}</text>
                            </view>
                        </view>

                        <view class="item-images" v-if="item.images">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredGrowthRecords.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 无数据提示 -->
        <empty-data v-if="filteredGrowthRecords.length === 0 && !loading" />

        <view
            class="add-button"
            @click="navigateTo('/pages/agriculture/growthManagement/addGrowthRecord')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { growth } from '@/utils/api/index.js'
// 导入格式化函数
import { formatDateChinese, formatImages } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'
import * as land from '@/utils/api/land.js'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            title: '作物生长记录',
            activeTab: 'all',
            searchKeyword: '',
            growthRecords: [],
            loading: false,
            loadingMore: false, // 加载更多状态
            hasMore: true, // 是否还有更多数据
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
            // 筛选相关数据
            selectedTime: '',
            selectedGrowthStage: '',
            selectedArea: '',
            startDate: '',
            endDate: '',
            tempStartDate: '',
            tempEndDate: '',
            selectedAreaIndex: 0,
            growthStageOptions: [],
            areaOptions: [{ id: 0, name: '选择地块' }],
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
        }),
        filteredGrowthRecords() {
            return this.growthRecords
        },
        // 计算当前筛选状态
        hasActiveFilters() {
            return (
                this.selectedTime ||
                (this.selectedGrowthStage && this.selectedGrowthStage.id) ||
                (this.selectedArea && this.selectedAreaIndex > 0)
            )
        },
    },
    onLoad() {
        // 确保字典数据已加载
        this.loadDictData()
        this.fetchAreaOptions()
    },
    onShow() {
        this.fetchGrowthRecords()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchGrowthRecords()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                uni.showLoading({ title: '加载字典数据...' })

                // 加载作物类型字典
                await this.getDictByType('crop_name_type')

                // 加载生长阶段字典
                const dictList = this.getDictByType('generation_phase')
                this.growthStageOptions = dictList.map((item) => {
                    return {
                        name: item.label,
                        id: item.value,
                    }
                })

                uni.hideLoading()
            } catch (error) {
                console.error('加载字典数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载字典数据失败',
                    icon: 'none',
                })
            }
        },

        // 获取地块选项
        async fetchAreaOptions() {
            try {
                const res = await land.getAllParcelAndFields()
                if (res.code === 0 && res.data && res.data.length > 0) {
                    this.areaOptions = [
                        { id: 0, name: '选择地块' },
                        ...res.data.map((parcel) => ({
                            id: parcel.id,
                            name: parcel.parcelName,
                        })),
                    ]
                } else {
                    this.areaOptions = [{ id: 0, name: '选择地块' }]
                }
            } catch (e) {
                this.areaOptions = [{ id: 0, name: '选择地块' }]
            }
        },

        // 统一处理筛选变化
        handleFilterChange() {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.growthStage
            delete this.pageParams.plotId

            // 时间筛选
            if (this.startDate && this.endDate) {
                this.pageParams.startDate = this.startDate
                this.pageParams.endDate = this.endDate
            }
            // 生长阶段筛选
            if (this.selectedGrowthStage && this.selectedGrowthStage.id) {
                this.pageParams.growthStage = this.selectedGrowthStage.id
            }
            // 地块筛选
            if (this.selectedArea) {
                this.pageParams.plotId = this.selectedArea
            }

            // 重新请求接口
            this.fetchGrowthRecords()
        },

        // 处理搜索变化
        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKeyword) {
                this.pageParams.keyword = e || this.searchKeyword
            } else {
                delete this.pageParams.keyword
            }

            // 重新请求接口
            this.fetchGrowthRecords()
        },

        async fetchGrowthRecords(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await growth.getGrowthRecordsPage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.growthRecords = [...this.growthRecords, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.growthRecords = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                } else {
                    // 如果API请求失败，使用默认数据
                    if (!isLoadMore) {
                        this.growthRecords = this.getDefaultData()
                        if (res.msg) {
                            uni.showToast({
                                title: res.msg || '获取数据失败',
                                icon: 'none',
                            })
                        }
                    }
                }
            } catch (error) {
                console.error('获取生长记录失败:', error)
                uni.showToast({
                    title: '获取数据失败',
                    icon: 'none',
                })
                // 使用默认数据
                if (!isLoadMore) {
                    this.growthRecords = this.getDefaultData()
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 获取默认数据，在API请求失败时使用
        getDefaultData() {
            return [
                {
                    id: 1,
                    measureDate: '2023-06-15',
                    cropName: '水稻-花优14',
                    plotId: '1号地块',
                    fieldId: '1号条田',
                    growthStage: '分蘖期',
                    leafArea: '45.3',
                    plantHeight: '68.5',
                    leafAge: '5.2',
                    images: '/static/images/crops/rice-growth-1.jpg,/static/images/crops/rice-growth-2.jpg',
                },
            ]
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.fetchGrowthRecords(true)
        },

        navigateTo(url) {
            uni.navigateTo({
                url,
            })
        },

        formatDate(dateString) {
            return formatDateChinese(dateString)
        },

        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        viewDetail(item) {
            // 跳转到详情页面
            uni.navigateTo({
                url: `/pages/agriculture/growthManagement/addGrowthRecord?id=${item.id}`,
            })
        },

        editRecord(item) {
            // 编辑记录，跳转到编辑页面
            uni.navigateTo({
                url: `/pages/agriculture/growthManagement/addGrowthRecord?id=${item.id}`,
            })
        },

        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条生长记录吗？`,
                success: (res) => {
                    if (res.confirm) {
                        this.deleteRecord(item.id)
                    }
                },
            })
        },

        async deleteRecord(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await growth.deleteGrowthRecord(id)

                if (res.code === 0) {
                    // 删除成功，更新列表
                    const index = this.growthRecords.findIndex((item) => item.id === id)
                    if (index !== -1) {
                        this.growthRecords.splice(index, 1)
                    }

                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除生长记录失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 日期选择相关方法
        onStartDateChange(e) {
            this.tempStartDate = e.detail.value
            if (this.tempEndDate && this.tempEndDate < this.tempStartDate) {
                this.tempEndDate = ''
            }
        },

        onEndDateChange(e) {
            this.tempEndDate = e.detail.value
            if (this.tempStartDate && this.tempEndDate < this.tempStartDate) {
                uni.showToast({
                    title: '结束日期不能早于开始日期',
                    icon: 'none',
                })
                this.tempEndDate = this.tempStartDate
            }
        },

        confirmDatePicker() {
            if (this.tempStartDate && this.tempEndDate) {
                if (this.tempEndDate < this.tempStartDate) {
                    uni.showToast({
                        title: '结束日期不能早于开始日期',
                        icon: 'none',
                    })
                    return
                }
                this.startDate = this.tempStartDate
                this.endDate = this.tempEndDate
                this.selectedTime = `${this.startDate} 至 ${this.endDate}`
                this.$refs.datePopup.close()
                this.handleFilterChange()
            } else {
                uni.showToast({
                    title: '请选择开始和结束日期',
                    icon: 'none',
                })
            }
        },

        cancelDatePicker() {
            this.tempStartDate = this.startDate
            this.tempEndDate = this.endDate
            this.$refs.datePopup.close()
        },

        openDatePopup() {
            this.$refs.datePopup.open()
        },

        // 生长阶段选择
        onGrowthStageChange(e) {
            const index = e.detail.value
            this.selectedGrowthStage = this.growthStageOptions[index]
            this.handleFilterChange()
        },

        // 地块选择
        onAreaChange(e) {
            const index = e.detail.value
            this.selectedAreaIndex = index
            if (index > 0) {
                this.selectedArea = this.areaOptions[index].id // 选中的地块id
            } else {
                this.selectedArea = ''
            }
            this.handleFilterChange()
        },

        // 清除所有筛选条件
        clearAllFilters() {
            this.selectedTime = ''
            this.selectedGrowthStage = ''
            this.selectedArea = ''
            this.selectedAreaIndex = 0
            this.startDate = ''
            this.endDate = ''
            this.tempStartDate = ''
            this.tempEndDate = ''
            this.searchKeyword = ''

            // 清除搜索参数
            delete this.pageParams.keyword
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.growthStage
            delete this.pageParams.plotId

            // 重新请求接口
            this.fetchGrowthRecords()
        },

        // 获取生长阶段文本
        getGrowthStageText(growthStage) {
            if (!growthStage) return '未知'

            // 尝试从字典获取
            const dictLabel = this.getDictLabel('generation_phase', growthStage)
            if (dictLabel) return dictLabel

            // 如果字典中没有，返回原值
            return growthStage || '未知阶段'
        },
    },
}
</script>

<style lang="scss" scoped>
.list-filter-container {
    display: flex;
    justify-content: space-between;
    padding: 10px;

    .filter-picker {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 0 5px;
        padding: 10px 12px;
        background-color: #fff;
        border: 1px solid #e5e5e5;
        border-radius: 8px;
        font-size: 15px;
        color: #333;
        position: relative;
        min-width: 0;
        box-sizing: border-box;

        .picker-label {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            text-align: left;
        }

        .picker-arrow {
            margin-left: 8px;
            font-size: 13px;
            color: #999;
        }
    }
}

.popup-content {
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 20px;

    .popup-title {
        font-size: 18px;
        font-weight: bold;
        text-align: center;
        margin-bottom: 20px;
    }

    .date-picker-container {
        margin-bottom: 20px;

        .date-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;

            .picker-value {
                flex: 1;
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 5px;
                text-align: center;
                width: 300rpx;
            }
        }
    }

    .popup-buttons {
        display: flex;
        justify-content: space-between;

        .btn {
            flex: 1;
            margin: 0 5px;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
            font-size: 16px;

            &.cancel {
                background-color: #f5f5f5;
                color: #333;
            }

            &.confirm {
                background-color: #2e6140;
                color: #fff;
            }
        }
    }
}
</style>
